package com.ruoyi.dynamic.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.enums.CacheKey;
import com.ruoyi.common.redis.cache.CacheTemplate;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.dynamic.mapper.GiftMapper;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.Gift;
import com.ruoyi.dynamic.model.pojo.request.app.AppChatRoomMessage;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomMaiUserResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppUserInfoResult;
import com.ruoyi.dynamic.service.IMessageService;
import io.rong.RongCloud;
import io.rong.methods.chatroom.entry.ChatroomEntry;
import io.rong.methods.chatroom.gag.Gag;
import io.rong.methods.message.chatroom.Chatroom;
import io.rong.models.chatroom.ChatroomEntryModel;
import io.rong.models.chatroom.ChatroomMember;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.message.ChatroomMessage;
import io.rong.models.response.ResponseResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义发送融云消息 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-11-27
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<GiftMapper, Gift> implements IMessageService {
    @Autowired
    private RongCloud rongCloud;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Async
    @SneakyThrows
    @Override
    public synchronized void setRoomChatRoomAttr(String chatRoomId, String userId, String key, String value, Integer autuDele, String objectName, String content) {
        log.info("设置聊天室属性-------chatRoomId={},key={}", chatRoomId, key);
        ChatroomEntryModel entryModel = new ChatroomEntryModel();
        entryModel.setChatroomId(chatRoomId);
        entryModel.setUserId(userId);
        entryModel.setValue(value);
        entryModel.setKey(key);
        entryModel.setObjectName(objectName);
        entryModel.setAutoDelete(autuDele);
        entryModel.setContent(content);
        ChatroomEntry entry = rongCloud.chatroom.entry;
        ResponseResult responseResult = entry.set(entryModel);
        log.info("响应参数-------responseResult={}", responseResult.getReqBody());
    }


    @Override
    public void removeRoomKV(String chatRoomId, String userId, String key, String objectName, String content) {
        ChatroomEntryModel entryModel = new ChatroomEntryModel();
        entryModel.setChatroomId(chatRoomId);
        entryModel.setUserId(userId);
        entryModel.setKey(key);
        entryModel.setObjectName(objectName);
        entryModel.setContent(content);
        ChatroomEntry entry = rongCloud.chatroom.entry;
        try {
            ResponseResult responseResult = entry.set(entryModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    @Override
    public void banByUser(String chatRoomId, String userId, Integer minute) {
        ChatroomMember[] members = {
                new ChatroomMember().setId(userId)
        };
        ChatroomModel model = new ChatroomModel();
        model.setId(chatRoomId);
        model.setMembers(members);
        model.setMinute(minute);
        Gag gag = rongCloud.chatroom.gag;
        ResponseResult add = gag.add(model);
        log.info("聊天室禁言某个用户-----add={}", add.getReqBody());
    }

    @SneakyThrows
    @Override
    public void cancelBanByUser(String chatRoomId, String userId) {
        ChatroomMember[] members = {
                new ChatroomMember().setId(userId)
        };
        ChatroomModel model = new ChatroomModel();
        model.setId(chatRoomId);
        model.setMembers(members);
        Gag gag = rongCloud.chatroom.gag;
        ResponseResult remove = gag.remove(model);
        log.info("聊天室取消禁言某个用户-----add={}", remove.toString());
    }

    @Async
    @SneakyThrows
    @Override
    public void sendCustomMessage(String fromUserId, String toChatroomId, String objectName, AppRoomMaiUserResult result, String msgType) {
        AppChatRoomMessage chatRoomMessage = new AppChatRoomMessage();
        chatRoomMessage.setUser(JSONObject.toJSONString(result));
        chatRoomMessage.setJsonStr("");
        chatRoomMessage.setMaiNum(result.getMaiNum().toString());
        chatRoomMessage.setObjectName(objectName);
        chatRoomMessage.setMsgType(msgType);

        ChatroomMessage message = new ChatroomMessage();
        message.setContent(chatRoomMessage);
        message.setObjectName(objectName);
        message.setContent(chatRoomMessage);
        message.setPriority(2);//高优先级消息
        message.setIsIncludeSender(1);
        message.setSenderId(fromUserId);
        String[] tar = new String[]{toChatroomId};
        message.setTargetId(tar);

        Chatroom chatroom = rongCloud.message.chatroom;
        ResponseResult send = chatroom.send(message);
        log.info("发送聊天室自定义消息=========send={}", send.getReqBody());
    }

    @Override
    public void updateRoomLineNum(Long id, String groupId, Long userId) {
        String key = CacheKey.ROOM_ONLINE.getKey("*");
        String cacheKey = key.replaceAll("\\{roomNumber}", String.valueOf(id));
        Collection<String> keys = redisService.keys(cacheKey);
        setRoomChatRoomAttr(groupId, userId.toString(), RoomChatRoomKvConstant.ROOM_LINE_NUM, String.valueOf(keys.size()), 0, "", "");
    }

    @Async
    @Override
    public void sendRoomRank(String groupId, String roomUserId, Long roomId, Long userId, BigDecimal giftPrice) {
        String key = CacheKey.ROOM_RANK.getKey("RANK");
        String cacheKey = key.replaceAll("\\{roomNumber}", String.valueOf(roomId));
        AppUserInfoResult cache = CacheTemplate.getCache(CacheKey.USER_INFO.getKey(String.valueOf(userId)), AppUserInfoResult.class);

        ZSetOperations<String, String> setOperations = redisTemplate.opsForZSet();
        Set<String> stringSet = CacheTemplate.insertAndGetRank(cacheKey, cache, giftPrice.doubleValue());
        List<AppUserInfoResult> appUserInfoResults = stringSet.stream().map(res -> {
            Double score = setOperations.score(cacheKey, res);
            AppUserInfoResult appUserInfoResult = JSONObject.parseObject(res, AppUserInfoResult.class);
            appUserInfoResult.setContrNum(new BigDecimal(BigDecimal.valueOf(score).stripTrailingZeros().toPlainString()));
            return appUserInfoResult;
        }).collect(Collectors.toList());


        setRoomChatRoomAttr(groupId, roomUserId, RoomChatRoomKvConstant.ROOM_RANK, JSONObject.toJSONString(appUserInfoResults), 0, "", "");


        String heatKey = RoomChatRoomKvConstant.ROOM_HEAT + roomId;
        BigDecimal bigDecimal = CacheTemplate.insertRoomVote(heatKey, roomId, giftPrice.doubleValue());
        setRoomChatRoomAttr(groupId, roomUserId, RoomChatRoomKvConstant.ROOM_HEAT, JSONObject.toJSONString(bigDecimal), 0, "", "");

    }

    @Override
    public void sendRoomRankAimUser(String groupId, String roomUserId, Long roomId, Long userId, BigDecimal giftPrice, Long aimUserId) {
        String key = CacheKey.ROOM_MOMENT_RANK.getKey(String.valueOf(aimUserId));
        String cacheKey = key.replaceAll("\\{roomNumber}", String.valueOf(roomId));

        AppUserInfoResult cache = CacheTemplate.getCache(CacheKey.USER_INFO.getKey(String.valueOf(userId)), AppUserInfoResult.class);

        ZSetOperations<String, String> setOperations = redisTemplate.opsForZSet();
        Set<String> stringSet = CacheTemplate.insertAndGetRank(cacheKey, cache, giftPrice.doubleValue());

        List<AppUserInfoResult> appUserInfoResults = stringSet.stream().map(res -> {
            Double score = setOperations.score(cacheKey, res);
            AppUserInfoResult appUserInfoResult = JSONObject.parseObject(res, AppUserInfoResult.class);
            appUserInfoResult.setContrNum(new BigDecimal(BigDecimal.valueOf(score).stripTrailingZeros().toPlainString()));
            return appUserInfoResult;
        }).collect(Collectors.toList());

        setRoomChatRoomAttr(groupId, roomUserId, RoomChatRoomKvConstant.ROOM_AUCTION_RANK, JSONObject.toJSONString(appUserInfoResults), 0, "", "");

    }


}
